<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="service.GoodsService" %>
<%@ page import="model.Goods" %>

<%
    // 获取商品ID并查询商品信息
    String goodsId = request.getParameter("id");
    if (goodsId != null) {
        GoodsService goodsService = new GoodsService();
        Goods goods = goodsService.getGoodsById(Integer.parseInt(goodsId));
        request.setAttribute("g", goods);
    }
%>
<html>
<head>
    <title>${g.name} - 商品详情</title>
    <script src="js/jquery.min.js"></script>
    <script src="js/layer.js"></script>
    <link rel="stylesheet" href="css/detail.css">
</head>
<body>
<div class="wai">
    <jsp:include page="navigation.jsp"/>
    <div class="container">
        <div class="product-details">
            <div class="product-image">
                <img src=".${g.cover}" alt="${g.name}">
            </div>
            <div class="product-info">
                <h1 class="product-title">${g.name}</h1>
                <div class="product-type">
                    分类：<a href="goods_list_jsp?typeid=${g.type.id}">${g.type.name}</a>
                </div>
                <div class="product-price">
                    ￥${g.price}
                </div>
                <div class="stock-info">
                    库存：${g.stock}件
                </div>
                <div class="product-description">
                    <h3>商品介绍</h3>
                    ${g.intro}
                </div>
                <button class="buy-button" onclick="buy(${g.id})">加入购物车</button>
            </div>
        </div>
    </div>
</div>

<script>

    // 在所有页面中统一使用以下方式显示提示消息
    function showMessage(msg) {
        if (typeof layer !== 'undefined') {
            layer.msg(msg);
        } else {
            alert(msg);
        }
    }

    // 修改buy函数
    function buy(goodsId) {
        $.ajax({
            url: "goods_buy?goodsid=" + goodsId,
            type: "POST",
            success: function (data) {
                if (data == "ok") {
                    alert("添加到购物车成功!");

                } else if (data == "fail") {
                    alert("库存不足!");
                }
            },
            error: function () {
                alert("添加失败，请稍后重试!");
            }
        });
    }
</script>
</body>
</html>
